import {messages} from "share/common";
import config from 'config'
/**
 * Created by 13576 on 2017/11/25.
 */
import React from 'react'
import {connect} from 'react-redux'
import {Button, Badge, message} from 'antd'
import SlideFrame from 'components/slide-frame'
import SearchArea from 'components/search-area'
import WrappedBOGEntityCard from 'containers/setting/bog-entity-card-stock/new-bog-entity-card-stock'
import BOGEntityCardService from 'containers/setting/bog-entity-card-stock/bog-entity-card-stock.service'
import 'styles/pay-setting/payment-method/payment-method.scss'
import ResizeTable from 'components/resize-table'
import ImportModal from "components/template/import-modal-ie/import-modal";
import ExportModal from 'components/template/export-modal/export-modal';

const exportList = [ //导出数据列表
  {
    type: 1002,
    command: "user_full_info",
    name: messages('enterprise-manage.key303'/*人员信息数据*/)
  },
];

class BOGEntityCard extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      cacheObj: {
      },//缓存变量
      CREATE_DATA_TYPE: true,
      loading: false,
      showImportPersonModel: false,
      progressImportErrInfo: 1,
      showImportErrInfo: false,
      transactionOID: null,
      errorsList: [
        {
          line: "",
          msg: ""
        },
      ],
      fileList: [],
      flieUploading: false,//文件是否正在上传
      exportList,
      pagination: {
        page: 0,
        total: 0,
        pageSize: 10,
      },
      data: [],
      timestamp:(new Date()).valueOf(),
      columns: [
        {
          title: "卡券编码",
          dataIndex: 'cardCode',
          key: 'cardCode',
          // render: value => {
          //   const {mappingList} = this.state;
          //   let res = '';
          //   mappingList.map(item => {
          //     value === item.value && (res = item.label);
          //   });
          //   return res;
          // }
        },
        {
          title: '卡券名称',
          dataIndex: 'cardName',
          key: 'cardName',
        },
        {
          title: '费用承担公司',
          dataIndex: 'costBearingCompany',
          key: 'costBearingCompany',
        },
        {
          title: '期初额',
          dataIndex: 'openingAmount',
          key: 'openingAmount',
        },
        {
          title: '发生额',
          dataIndex: 'amountIncurred',
          key: 'amountIncurred',
        },
        {
          title: '余额',
          dataIndex: 'balance',
          key: 'balance',
        },
        {
          title: '有效期间（年）',
          dataIndex: 'year',
          key: 'year',
        },
        {/*状态*/
          title: messages('pay-setting.key58'/*状态*/),
          dataIndex: 'enable',
          key: 'enable',
          render: (recode, text) => {
            return (<div ><Badge status={ recode ? "success" : "error"}/>
              {recode ? messages('common.status.enable') : messages('common.status.disable')}
            </div>);
          }
        },
      ],
      searchForm: [
        {type: 'input', id: 'cardCode', label: '卡券编码'},
        {type: 'input', id: 'cardName', label: '卡券名称'},
        {
          type: 'list',
          id: 'companyName',
          label: messages('enterprise-manage.key313'/*公司*/),
          listType: 'all_company_with_legal_entity',
          labelKey: 'companyName',
          valueKey: 'companyName',
          placeholder: messages('enterprise-manage.key311'/*请选择*/),
        },
        {
          type: 'switch',
          id: 'enable',
          label: messages('enterprise-manage.key314'/*状态*/),
          // event: "enableChange",

        },
        {type: 'input', id: 'year', label: '有效期间'},
      ],
      pageSize: 10,
      page: 0,
      pagination: {
        total: 0
      },
      searchParams: {},
      updateParams: {},
      showSlideFrameNew: false,
      loading: true,
      mappingList: []
    };
  }


  componentWillMount() {
    this.getList();
  }


//获得数据
  getList=() => {
    console.log(this)
    let params = {};
    params.cardCode=this.state.searchParams.cardCode;
    params.cardName=this.state.searchParams.cardName;
    params.costBearingCompany=this.state.searchParams.costBearingCompany;
    params.year=this.state.searchParams.year;
    params.enable=this.state.searchParams.enable;
    params.size=this.state.pageSize;
    params.page=this.state.page;
    Promise.all([
      BOGEntityCardService.getBOGList(params),
    ]).then(res => {
      this.setState({
        data: res[0].data.records,
        loading: false,
        pagination: {
          total: Number(res[0].data.total),
          onChange: this.onChangePager,
          current: this.state.page + 1
        },
        // mappingList: temp
      })
    }).catch(() => {
      message.error(messages('pay-setting.key62'/*系统异常*/));
      this.setState({loading: false});
    });
  }

  //分页点击
  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1,
        loading: true
      }, () => {
        this.getList();
      })
  };


  //清空搜索区域
  clear = () => {
    this.setState({
      updateParams: {
      },
    })
  };

  //搜索
  search = (result) => {
    let searchParams = {
      cardCode: result.cardCode,
      cardName: result.cardName,
      costBearingCompany: result.companyName,
      year: result.year,
      enable: result.enable,
    };
    this.setState({
      searchParams: searchParams,
      loading: true,
      page: 0,
      current: 1
    }, () => {
      this.getList();
    })
  };


  handleCloseNewSlide = (params) => {
    if(params) {
      this.setState({loading: true,showSlideFrameNew: false},() => {
        this.getList();
      });
    }
  };


  showSlideNew = (flag) => {
    this.setState({
      showSlideFrameNew: flag
    })
  };

  newItemTypeShowSlide = () => {
    let timestamp = (new Date()).valueOf();
    this.setState({
      timestamp,
      updateParams: {},
    }, () => {
      this.showSlideNew(true)
    })
  }

  putItemTypeShowSlide = (recode) => {
    let timestamp = (new Date()).valueOf();
    this.setState({
      updateParams: recode,
      timestamp
    }, () => {
      this.showSlideNew(true)
    })

  }


  render() {
    let exportCondition = Object.assign({}, {cardDownloadCommand:this.state.searchParams}, {"sort": "status"});
    const templates = [
      {
        downloadName: "BOG实体卡库存模板",
        templateName: "BOG实体卡库存模板",
        downloadUrl: "/api/art/card/import/template",
        downloading: "loading"
      },]
    const { columns, data, pagination, searchForm, showSlideFrameNew, loading, updateParams, mappingList, timestamp } = this.state
    return (
      <div className="payment-method">
        <div className="searchFrom">
          <SearchArea
            searchForm={searchForm}
            submitHandle={this.search}
            clearHandle={this.clear}
            eventHandle={this.eventSearchAreaHandle}/>
        </div>

        <div className="table-header">
          <div
            className="table-header-title">{messages('common.total', {total: `${pagination.total}`})}</div>
          <div className="btnsContainer">
            {/* <Button 
              type="primary"
              onClick={this.newItemTypeShowSlide}>{messages('common.create') }
            </Button> */}
            <ImportModal 
              buttonName={"导入库存数据"}
              // leftContent={}
              templates={templates}
              hasErrInfo={true}
              uploadUrl={`${config.baseUrl}/api/art/card/import`}
              onCancel={this.getList}/>
            {/* &nbsp;&nbsp;&nbsp; */}
                <ExportModal
                  type="btn"
                  codeCheck={true}
                  exportTitle={"导出库存数据"}
                  exportType="BOG_CARD"
                  exportCondition={exportCondition}
                  exportCommand={"BOG_entity_card_stock"}
                  style={{marginLeft: 20}}
                />
          </div>
          
        </div>

        <div className="Table_div" style={{backgroundColor: 111}}>
          <ResizeTable
            columns={columns}
            dataSource={data}
            pagination={pagination}
            loading={loading}
            bordered
            // onRow={record => ({
            //   onClick: () => this.putItemTypeShowSlide(record)
            // })}
            size="middle"
          />
        </div>

        <SlideFrame title={JSON.stringify(this.state.updateParams) === "{}"?'新建BOG实体卡库存':'编辑BOG实体卡库存'}
                    show={showSlideFrameNew}
                    content={WrappedBOGEntityCard}
                    afterClose={this.handleCloseNewSlide}
                    onClose={() => this.showSlideNew(false)}
                    params={{
                      updateParams,
                      timestamp,
                      mappingList}}/>
      </div>
    );
  }

}

function mapStateToProps() {
  return {
  }
}

export default connect(mapStateToProps)(BOGEntityCard);
